package com.imau.servlet;

import com.imau.bean.User;
import com.imau.mapper.UserMapper;
import com.imau.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private SqlSession sqlSession;
    private UserMapper userMapper;

    @Override
    public void init() throws ServletException {
        try {
            sqlSession = SqlSessionUtil.getSqlSession();
            userMapper = sqlSession.getMapper(UserMapper.class);
        } catch (Exception e) {
            throw new ServletException("初始化 MyBatis 失败", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        try {
            if (userMapper.selectByUserName(username) != null) {
                resp.getWriter().write("用户名已存在！");
            } else if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
                resp.getWriter().write("用户名和密码不能为空！");
            } else {
                User user = new User(null, username, password);
                int i = userMapper.insertUser(user);
                if (i > 0) {
                    sqlSession.commit();
                    resp.sendRedirect(req.getContextPath() + "/login.html");
                } else {
                    resp.getWriter().write("注册失败！");
                }
            }
        } catch (Exception e) {
            resp.sendError(500, "服务器错误: " + e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    public void destroy() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}